package top.springcloud.customer.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.springcloud.customer.entity.Customer;
import top.springcloud.customer.service.CustomerService;

/**
 * 提供服务，供消费者调用
 */
@RequestMapping("/customer/")
@RestController
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private DiscoveryClient client;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("get/{customerId}")
    public Customer get(@PathVariable("customerId") Integer customerId){
        logRequestInfo("/customer/get/{customerId}");
        return customerService.getCustomerById(customerId);
    }

    @RequestMapping("save")
    public Customer save(@RequestBody Customer customer){
        logRequestInfo("/customer/save");
        logger.info("save customer: "+customer);
        return customerService.saveCustomer(customer);
    }

    private void logRequestInfo(String uri){
        client.getServices().forEach(id -> {
            client.getInstances(id).forEach(instance -> {
                logger.info("Request: "+uri+", host:" + instance.getHost() + " , port:"+instance.getPort()+
                        ", service_id:" + instance.getServiceId());
            });
        });
    }
}
